package com.example.demo.leetcode.top100;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * ******************************************************
 *
 * @author liugh9
 * @version 1.0
 * @classname _12最小覆盖子串
 * @description
 * @date 2023/06/05 21:48
 * <p>
 * ******************************************************
 */
public class _12最小覆盖子串 {
    public static String minWindow(String s, String t) {
        Map<Character, Integer> windows = new HashMap<>();
        Map<Character, Integer> needs = new HashMap<>();

        // 需要查找的字符串的字典
        for (char c : t.toCharArray()) {
            needs.put(c, needs.getOrDefault(c, 0) + 1);
        }

        // 双指针划分窗口
        int left = 0, right = 0;
        // 符合字符个数
        int valid = 0;
        // 记录结果
        String res = "";
        Integer resLength = Integer.MAX_VALUE;

        while (right < s.length()) {
            char curr = s.charAt(right);
            right++;
            windows.put(curr, windows.getOrDefault(curr, 0) + 1);
            if (needs.containsKey(curr)) {
                if (windows.get(curr).equals(needs.get(curr))) {
                    valid++;
                }
            }

            while (valid == needs.size()) {
                if (resLength > (right - left)) {
                    res = s.substring(left, right);
                    resLength = (right - left);
                }
                char d = s.charAt(left);
                left++;
                if (needs.containsKey(d) && windows.get(d).equals(needs.get(d))) {
                    valid--;
                }
                windows.put(d, windows.get(d) - 1);
            }
        }
        return res;
    }

    public static void main(String[] args) {
        System.out.println(minWindow("ADOBECODEBANC", "ABC"));
    }
}
